import type { UserConfig } from 'vitepress'
import path from 'node:path'
import vueJsx from '@vitejs/plugin-vue-jsx'
import UnoCSS from 'unocss/vite'
import IconsResolver from 'unplugin-icons/resolver'
import Icons from 'unplugin-icons/vite'
import Components from 'unplugin-vue-components/vite'
import { MarkdownTransform } from '../plugins/markdown-transform'

type ViteConfig = Required<UserConfig>['vite']
type ResolveOptions = Required<ViteConfig>['resolve']
type AliasOptions = Required<ResolveOptions>['alias']

export function getViteConfig(): UserConfig {
  const alias: AliasOptions = [
    {
      find: '~/',
      replacement: `${path.resolve(__dirname, '../vitepress')}/`,
    },
  ]
  return {
    css: {
      preprocessorOptions: {
        scss: {
          silenceDeprecations: ['legacy-js-api'],
        },
      },
    },
    resolve: {
      alias,
    },
    plugins: [
      vueJsx(),
      // https://github.com/antfu/unplugin-vue-components
      Components({
        dirs: ['.vitepress/vitepress/components'],
        allowOverrides: true,
        // custom resolvers
        resolvers: [
          // auto import icons
          // https://github.com/antfu/unplugin-icons
          IconsResolver(),
        ],
        // allow auto import and register components used in markdown
        include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
      }),
      // https://github.com/antfu/unplugin-icons
      Icons({
        autoInstall: true,
      }),
      UnoCSS({
        inspector: false,
      }),
      MarkdownTransform(),
    ],
    // 解决开发服务器刷新问题
    optimizeDeps: {
      include: ['@iconify/json'],
    },
  } as UserConfig
}
